import java.util.HashMap;
import java.util.Map;

/**
 * @Author ZhangCuirong
 * @Date 2025/9/4 15:32
 * @description:
 */
public class Solution974 {
    public int subarraysDivByK(int[] nums, int k) {
        int[] prefixSum = new int[nums.length + 1];
        for (int i = 0; i < nums.length; i++) {
            prefixSum[i + 1] = prefixSum[i] + nums[i];
        }
        Map<Integer, Integer> map = new HashMap<>();
        int count = 0;
        // 修正1：处理初始化时的负数余数（转为非负）
        int initRemainder = (prefixSum[0] % k + k) % k;
        map.put(initRemainder, 1);
        for (int end = 1; end <= nums.length; end++) {
            int reminder = (prefixSum[end] % k + k) % k;
            if (!map.containsKey(reminder)) {
                map.put(reminder, 1);
            } else {
                count += map.get(reminder);
                map.put(reminder, map.get(reminder) + 1);
            }
        }
        return count;
    }

    public static void main(String[] args) {
        Solution974 solution = new Solution974();
        System.out.println(solution.subarraysDivByK(new int[]{4, 5, 0, -2, -3, 1}, 5));
        System.out.println(solution.subarraysDivByK(new int[]{5}, 9));
    }
}
